package com.programmercarl.backtracking;

import javax.script.ScriptException;
import java.util.*;

/**
 * https://leetcode.cn/problems/combination-sum-ii/description/
 * 组合总和
 *
 * @author yulongtian
 * @create 2025-01-07 9:29
 */
public class Test05 {
    public static void main(String[] args) throws ScriptException {

    }

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Deque<Integer> path = new LinkedList<Integer>();
        Arrays.sort(candidates);
        boolean[] used = new boolean[candidates.length];
        backtrack(candidates, used, target, 0, 0, res, path);
        return res;
    }

    public void backtrack(int[] candidates, boolean[] used, int target, int sum, int start, List<List<Integer>> res, Deque<Integer> path) {
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = start; i < candidates.length && sum + candidates[i] <= target; i++) {
            if (i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]) {
                continue;
            }
            used[i] = true;
            path.push(candidates[i]);
            backtrack(candidates, used, target, sum + candidates[i], i + 1, res, path);
            used[i] = false;
            path.pop();

        }
    }

}
